﻿using Modbus.Data;
using Modbus.Device;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ModbusSlaveDemo
{
    public partial class FormMain : Form
    {
        private ModbusSlave _modbusServer = null;
        private DataStore _dataStore = null;

        public FormMain()
        {
            InitializeComponent();
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            var _ip = new IPAddress(new byte[] { 127, 0, 0, 1 });
            var _listener = new TcpListener(_ip, 502);

            _modbusServer = ModbusTcpSlave.CreateTcp(1, _listener);

            _dataStore = DataStoreFactory.CreateDefaultDataStore(); ;
            _modbusServer.DataStore = _dataStore;

            _modbusServer.ModbusSlaveRequestReceived += _modbusServer_ModbusSlaveRequestReceived;
            _modbusServer.WriteComplete += _modbusServer_WriteComplete;
        }      

        private void _modbusServer_ModbusSlaveRequestReceived(object sender, ModbusSlaveRequestEventArgs e)
        {
            string str = "";
            foreach (var item in e.Message.MessageFrame)
            {
                str += item.ToString("x2").PadLeft(2, '0').ToUpper() + "  ";
            }
            Debug.WriteLine("RequestReceived:" + e.Message + ":" + str);
        }

        private void _modbusServer_WriteComplete(object sender, ModbusSlaveRequestEventArgs e)
        {
            Debug.WriteLine("WriteComplete:" + e.Message);
        }

        private void btnListen_Click(object sender, EventArgs e)
        {
            Task.Run(() =>
            {
                _modbusServer?.Listen();
            });

            timer1.Enabled = true;
            btnListen.Enabled = false;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            string str = "";
            for (int i = 1; i <= 10; i++)
            {
                str += _dataStore?.HoldingRegisters[i].ToString() + "  ";
            }
            this.txtData.Text = str;
        }
    }
}
